#!/usr/bin/env python3

import numpy as np
import math
import os
import cloudComPy as cc
import subprocess

dataDir = os.path.join(os.environ["@USER_HOME@"], "@PYTHONAPI_TEST_DIRECTORY@")
if not os.path.exists(dataDir):
    os.makedirs(dataDir)

def isCoordEqual(vals, refs, tol=1.e-6):
    for val, ref in zip(vals, refs):
        if not math.isclose(val, ref, rel_tol=tol):
            return False
    return True


def getSampleCloud(h=5.0, dx=0):
    dataName = "dataSample_%s.xyz" % h
    if dx != 0:
        dataName = "dataSample_%s_%s.xyz" % (h,dx)
    sample = os.path.join(dataDir, dataName)
    if not os.path.exists(sample):
        vx = np.arange(-5+dx, 5+dx, 0.01)
        vy = np.arange(-5, 5, 0.01)

        with open(sample, 'w') as f:
            for x in vx:
                for y in vy:
                    z = math.sin(h * math.sqrt(x**2 + y**2)) / math.sqrt(x**2 + y**2)
                    f.write("%f %f %f\n" % (x, y, z))
    return sample

def getSampleCloud2(h=5.0, dx=0, step=0.01):
    dataName = "dataSample2_%s_%s_%s.xyz" % (h,dx,step)
    sample = os.path.join(dataDir, dataName)
    if True: #not os.path.exists(sample):
        vx = np.arange(-5+dx, 5+dx, step)
        vy = np.arange(-5, 5, step)

        with open(sample, 'w') as f:
            for x in vx:
                for y in vy:
                    z = math.sin(h * math.sqrt((0.5*x)**2 + y**2)) / math.sqrt((0.5*x)**2 + y**2)
                    f.write("%f %f %f\n" % (x, y, z))
    return sample

def getSamplePoly(polyname="poly1"):
    dataName = "%s.poly" % polyname
    sample = os.path.join(dataDir, dataName)
    if not os.path.exists(sample):
        vx = []
        vy = []
        if polyname == "poly1":
            vx = [ 1.,  2.,  3.,  2., -1., -1., -2.]
            vy = [ 2.,  4.,  1., -2., -3., -1.,  2.]
        with open(sample, 'w') as f:
            for x,y in zip(vx, vy):
                f.write("%f %f %f\n" % (x, y, 0.))
    return sample

def getSamplePoly2(polyname="poly2"):
    dataName = "%s.poly" % polyname
    sample = os.path.join(dataDir, dataName)
    if not os.path.exists(sample):
        vx = []
        vy = []
        if polyname == "poly2":
            vx = [-4.,  0.,  4., 3.5,  4.,  0., -4.,-3.5]
            vy = [ 4., 3.5,  4.,  0., -4.,-3.5, -4.,  0.]
        with open(sample, 'w') as f:
            for x,y in zip(vx, vy):
                f.write("%f %f %f\n" % (x, y, 0.))
    return sample


def createSymbolicLinks():
    modulePath = cc.__file__
    mpath = os.path.dirname(modulePath)
    d = mpath.split(os.sep)[-1]
    if d == 'boostPython':  # we are on build
        command = ""
        command += "cd %s ;" % mpath
        command += "cd ../CloudCompare/plugins ;"
        command += "rm -f *.so ;"
        command += 'find . -name "*.so" -exec ln -s {} . \;'
        print(command)
        p = subprocess.Popen(command, shell=True)
